import * as vscode from 'vscode';
import * as axios from 'axios';

//网易的数据
const apiUrl: string = 'https://api.money.126.net/data/feed/';
const clickCommand: string = 'zj-vscode-stock.onClick';
let statusBarItems: any = {};
let stockCodes: any = [];
let interval: number | undefined = 10000;
let timer: any = null;
let isShow: boolean = true;
let showButton: any = null;

export function activate(context: vscode.ExtensionContext) {
	vscode.window.showInformationMessage('激活ZJ Stock插件');
	init();
	createStatusBarBtn();
	context.subscriptions.push(
		vscode.workspace.onDidChangeConfiguration(onConfigChange)
	);
	context.subscriptions.push(vscode.commands.registerCommand(clickCommand, () => {
		isShow = !isShow;
		onConfigChange();
	}));
}

export function deactivate() { }

function init() {
	const config = vscode.workspace.getConfiguration();
	stockCodes = getStockCodes();
	interval = config.get('zj-vscode-stock.interval');
	requestData();
	timer = setInterval(requestData, interval);
}

function onConfigChange() {
	timer && clearInterval(timer);
	const stockCodes = getStockCodes();
	Object.keys(statusBarItems).forEach((item) => {
		if (stockCodes.indexOf(item) === -1 || !isShow) {
			statusBarItems[item].hide();
			statusBarItems[item].dispose();
			delete statusBarItems[item];
		}
	});
	if(isShow) init();
	createStatusBarBtn();
}

function getStockCodes() {
	const config: any = vscode.workspace.getConfiguration();
	const stockCodes: any = config.get('zj-vscode-stock.codes');
	return stockCodes.split(',').map((code: any) => {
		if (isNaN(code[0])) {
			if (code.toLowerCase().indexOf('us_') > -1) {
				return code.toUpperCase();
			} else if (code.indexOf('hk') > -1) {
				return code;
			} else {
				return code.toLowerCase().replace('sz', '1').replace('sh', '0');
			}
		} else {
			return (code[0] === '6' ? '0' : '1') + code;
		}
	});
}


function itemText(item: any) {
	return `${item.name} ${price(item.price)}  ${percent(item.percent)}`;
}

function itemTooltip(item: any) {
	return `振幅：${price(item.updown)
		}\n成额：${turnover(item.turnover)}  --成量：${turnover(item.volume)
		}\n最高：${price(item.high)}  --最低：${price(item.low)}  --开盘：${price(item.open)}`;
}

function itemColor(item: any) {
	const config = vscode.workspace.getConfiguration();
	const colorUp = config.get('zj-vscode-stock.colorUp');
	const colorDown = config.get('zj-vscode-stock.colorDown');
	return item.percent >= 0 ? colorUp : colorDown;
}

function requestData() {
	// @ts-ignore
	axios.get(`${apiUrl}${stockCodes.join(',')}?callback=a`).then(
		(res: any) => {
			try {
				const data = JSON.parse(res.data.slice(2, -2));
				let list: any = [];
				Object.keys(data).map((item: any) => {
					if (!data[item].code) {
						data[item].code = item;
					}
					list.push(data[item]);
				});
				fixData(list);
			} catch (error) { }
		},
		(err: any) => {
			console.error(err);
		}
	).catch((err: any) => {
		console.error(err);
	});
}

function fixData(list: any) {
	list.map((item: any) => {
		if (statusBarItems[item.code]) {
			statusBarItems[item.code].text = itemText(item);
			statusBarItems[item.code].color = itemColor(item);
			statusBarItems[item.code].tooltip = itemTooltip(item);
		} else {
			statusBarItems[item.code] = createStatusBarItem(item);
		}
	});
}

function createStatusBarItem(item: any) {
	const statusBarItem: any = vscode.window.createStatusBarItem(
		vscode.StatusBarAlignment.Left,
		0 - stockCodes.indexOf(item.code)
	);
	statusBarItem.text = itemText(item);
	statusBarItem.color = itemColor(item);
	statusBarItem.tooltip = itemTooltip(item);
	statusBarItem.show();
	return statusBarItem;
}

function createStatusBarBtn() {
	if(showButton){
		showButton.hide();
		showButton.dispose();
		showButton = null;
	}
	showButton = vscode.window.createStatusBarItem(
		vscode.StatusBarAlignment.Left, 0 - stockCodes.length);
	showButton.text = isShow ? '隐藏' : '显示';
	showButton.color = 'white';
	showButton.command = clickCommand;
	showButton.show();
}

function price(num: any) {
	var tmp = parseFloat(num);
	if (isNaN(tmp)) return num;
	return tmp.toFixed(2);
}

function percent(num: any) {
	var tmp = parseFloat(num) * 100;
	if (isNaN(tmp)) return '--';
	return tmp.toFixed(2) + '%';
}

function turnover(num: any){
	var tmp = parseInt(num);
	if(tmp >= 10000 && tmp < 100000000){
		return Math.ceil(tmp / 10000) + '万';
	}
	if(tmp >= 100000000){
		return Math.ceil(tmp / 100000000) + '亿';
	}
	return num;
}
